//
//  ChatRecordView.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2020/8/18.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

protocol ChatRecordViewDelegate: NSObjectProtocol {
    func chatRecordViewSend(model: UploadAudioModel)
}

class ChatRecordView: UIView {
    
    weak var delegate: ChatRecordViewDelegate?
    var timer: Timer?
    var timerCount: CGFloat = 60.0
    let maxTimerCount: CGFloat = 60.0
    let repeatTimer: CGFloat = 0.15
    let recordManager: RecordManager = RecordManager.sharedInstance

    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func show() {
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 1
        })
    }
    
    func dismiss() {
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0
        }) { (finish) in
            self.removeFromSuperview()
        }
    }
    
    func setUI() {
        self.alpha = 0
        self.frame = CGRect(x: 0, y: 0, width: screenW, height: screenH)
        self.backgroundColor = UIColor.init(white: 0, alpha: 0.5)
        self.addSubview(bottomView)
        bottomView.addSubview(timeLabel)
        bottomView.addSubview(leftAnimationView)
        bottomView.addSubview(rightAnimationView)
        bottomView.addSubview(progressView)
        bottomView.addSubview(deleteImgBgView)
        deleteImgBgView.addSubview(deleteImgView)
        bottomView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(275)
        }
        progressView.snp.makeConstraints { (make) in
            make.width.height.equalTo(100)
            make.center.equalTo(bottomView.snp.center)
        }
        deleteImgBgView.snp.makeConstraints { (make) in
            make.centerY.equalTo(bottomView.snp.centerY)
            make.width.height.equalTo(58)
            make.centerX.equalTo(screenW / 2.0 + 45 + (screenW / 2.0 - 45) / 2.0)
        }
        deleteImgView.snp.makeConstraints { (make) in
            make.center.equalTo(deleteImgBgView.snp.center)
            make.width.equalTo(20)
            make.height.equalTo(24)
        }
        timeLabel.snp.makeConstraints { (make) in
            make.top.equalTo(30)
            make.centerX.equalToSuperview()
        }
        leftAnimationView.snp.makeConstraints { (make) in
            make.right.equalTo(timeLabel.snp.left).offset(-8)
            make.centerY.equalTo(timeLabel.snp.centerY)
            make.width.equalTo(51)
            make.height.equalTo(12)
        }
        rightAnimationView.snp.makeConstraints { (make) in
            make.left.equalTo(timeLabel.snp.right).offset(8)
            make.centerY.equalTo(timeLabel.snp.centerY)
            make.width.equalTo(51)
            make.height.equalTo(12)
        }
    }
    
    lazy var progressView: ChatRecordProgressView = {
        let rect = CGRect(x: screenW / 2.0 - 45 ,
                          y: (275 - 90) / 2.0 ,
                          width: 90,
                          height: 90)
        let progress = ChatRecordProgressView(frame: rect,
                                              lineWidth: 6)
        progress.setProgress(value: 0, base: maxTimerCount)
        return progress
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    lazy var deleteImgView: UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "chat_record_delete_normal"))
        return imgView
    }()
    
    lazy var deleteImgBgView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.init(hex: "#F5F6F6")
        view.layer.cornerRadius = 29
        view.layer.masksToBounds = true
        return view
    }()
    
    lazy var timeLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.medium(14)
        label.textColor = UIColor.mainColor
        label.textAlignment = .center
        label.text = "0:00"
        return label
    }()
    
    lazy var leftAnimationView : UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "chat_record_db_left0"))
        return imgView
    }()
    
    lazy var rightAnimationView : UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "chat_record_db_right0"))
        return imgView
    }()
}

extension ChatRecordView {
    func startTimer() {
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: TimeInterval(repeatTimer), target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        }
    }
    
    @objc func timerAction() {
        timerCount -= repeatTimer
//        print(String.init(format: "%.2f", timerCount))
        let progress = (maxTimerCount - timerCount) / maxTimerCount
        progressView.setProgress(value: progress, base: maxTimerCount)
        recordManager.recorder?.updateMeters()
        if let peakPower = recordManager.recorder?.peakPower(forChannel: 0) {
    //        let peakPowerForChannel = pow(10, (0.05 * peakPower));
    //        var lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;
            print(peakPower)
            print((peakPower + 160.0) / 160.0)
            let count = Int(peakPower + 160) % 5 + 1
            let leftImgName =  "chat_record_db_left\(count)"
            let rightImgName =  "chat_record_db_right\(count)"
            leftAnimationView.image = UIImage(named: leftImgName)
            rightAnimationView.image = UIImage(named: rightImgName)
        }
        timeLabel.text = String.init(format: "0:%02d", Int(maxTimerCount - timerCount))
        if timerCount <= 0 {
            timerStop(sendSucess: true)
        }
    }
    
    func timerStop(sendSucess: Bool) {
        timer?.invalidate()
        timer = nil
        timerCount = maxTimerCount
        timeLabel.text = "0:00"
        progressView.setProgress(value: 0, base: maxTimerCount)
        recordManager.stopRecord()
        deleteImgView.image = UIImage(named: "chat_record_delete_normal")
        dismiss()
        if sendSucess {
            if let time = recordManager.getAudioTime(path: recordManager.record_path), time < 1.0 {
                clearFile()
                clearMp3File()
                HUDTool.show(message: "说话时间太短")
                return
            }
            convertToMp3()
        } else {
            clearFile()
        }
    }
    
    func convertToMp3() {
        guard recordManager.getAudioTime(path: recordManager.record_path) != nil else {
            return
        }
        ConvertAudioFile.conventToMp3(withCafFilePath: recordManager.record_path ?? "", mp3FilePath: recordManager.mp3_path ?? "", sampleRate: 11025) { (finish) in
            if finish {
                print("mp3:-----\(self.recordManager.mp3_path ?? "")")
                dispatch_queue_global_t.main.async {
                    self.uploadAudio()
                }
            } else {
                print("mp3-----failed")
            }
        }
    }
    
    func uploadAudio() {
        guard let filePath = recordManager.mp3_path, let time =  recordManager.getAudioTime(path: recordManager.mp3_path) else {
            HUDTool.showError(message: "语音错误")
            return
        }
        HUDTool.showActivity()
        ChatViewModel.uploadIMAudio(filePath: filePath, time: Int(time), success: { (model) in
            HUDTool.hideActivity()
            guard let _ = model.shareUrl else {
                HUDTool.showError(message: "语音上传错误")
                return
            }
            self.delegate?.chatRecordViewSend(model: model)
        }) { (errorMsg) in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
        self.clearFile()
        self.clearMp3File()
    }
    
    func clearFile() {
        RecordManager.removefile(folderName: recordManager.record_path ?? "")
    }
    func clearMp3File() {
        RecordManager.removefile(folderName: recordManager.mp3_path ?? "")
    }
}

extension ChatRecordView: ChatSpeakViewDelegate {
    func chatSpeakViewLongPress(tap: UILongPressGestureRecognizer) {
        if tap.state == .began {
            guard recordManager.beginRecord() else {
                HUDTool.showError(message: "录音初始化错误")
                return
            }
            mainWindow.addSubview(self)
            show()
            self.startTimer()
        } else if tap.state == .changed {
            let point = tap.location(in: deleteImgBgView)
            if deleteImgBgView.layer.contains(point) {
                deleteImgView.image = UIImage(named: "chat_record_delete_select")
            } else {
                deleteImgView.image = UIImage(named: "chat_record_delete_normal")
            }
        } else if tap.state == .ended {
            guard timer != nil else { return }
            let point = tap.location(in: deleteImgBgView)
            if deleteImgBgView.layer.contains(point) {
                timerStop(sendSucess: false)
            } else {
                timerStop(sendSucess: true)
            }
        } else {
            HUDTool.show(message: "取消发送")
            timerStop(sendSucess: false)
        }
    }
}
